# apps/app01/views/order_views.py

from rest_framework import views, status
from rest_framework.response import Response

from apps.app01.models import Order, User
from apps.app01.views.delete_order.serializers import CancelOrderSerializer


class CancelOrderView(views.APIView):


    # permission_classes = [IsAuthenticated]  # 按需启用

    def post(self, request):
        # 1. 反序列化并校验请求体
        serializer = CancelOrderSerializer(data=request.data)
        if not serializer.is_valid():
            return Response(
                {
                    "code": 400,
                    "message": "参数错误",
                    "errors": serializer.errors
                },
                status=status.HTTP_400_BAD_REQUEST
            )

        # 2. 获取订单ID和当前用户
        order_id = serializer.validated_data.get('id')
        user_id = request.user['user_id']
        user = User.objects.get(id=user_id)
        # user = User.objects.first()  # 测试时可使用

        # if user.is_anonymous:
        #     return Response(
        #         {"code": 401, "message": "用户未登录"},
        #         status=status.HTTP_401_UNAUTHORIZED
        #     )

        # 3. 查询订单（确保订单属于当前用户）
        try:
            order_obj = Order.objects.get(order_id=order_id, user=user_id)
        except Order.DoesNotExist:
            return Response(
                {"code": 404, "message": "订单不存在或不属于当前用户"},
                status=status.HTTP_404_NOT_FOUND
            )

        # 4. 删除订单
        order_obj.delete()

        # 5. 返回成功响应
        return Response(
            {"code": 200, "message": "ok"},
            status=status.HTTP_200_OK
        )
